import React, { memo, useRef, FC } from 'react';
import { FormInstance } from 'antd/lib/form';
import CommonModal from '@/components/CommonModal';
import AddForm from './AddForm';
import useHoxModel from '../../useHoxModel';
import { modelName } from '../..';
import moment from 'moment';
import { PlanListReturnType } from '../../API';

interface Props {}

const ModalContent: FC<Props> = (props) => {
  const formRef = useRef<FormInstance>();
  const { addPlanMode, getPlanModeList, editPlanMode, planModeInfo } = useHoxModel((model) => [
    model.planModeInfo,
  ]);

  const confim = async <T extends {}>(
    cancel: () => void,
    request: (params: T) => Promise<any>,
    filterData?: (props: any) => Promise<any>,
  ) => {
    try {
      const fields: any = await formRef.current?.validateFields();
      const params = await (filterData ? filterData(fields) : fields);
      let res = await request(params);
      if (!(res.result < 0)) {
        getPlanModeList();
        cancel();
      }
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  };
  return (
    <>
      <CommonModal
        title="编辑模板"
        width={605}
        type={modelName + 'edit'}
        onOk={(cancelModal: (type?: string, clear?: boolean) => void) => {
          const filterData = async (fields: any) => {
            fields['startTime'] = moment(fields.time[0]).format('HH:mm');
            fields['endTime'] = moment(fields.time[1]).format('HH:mm');

            delete fields['time'];
            return { ...fields, id: planModeInfo?.id };
          };
          confim<PlanListReturnType>(cancelModal, editPlanMode, filterData);
        }}
      >
        <AddForm formRef={formRef} />
      </CommonModal>
      <CommonModal
        title="新增模板"
        width={605}
        type={modelName + 'add'}
        onOk={(cancelModal: (type?: string, clear?: boolean) => void) => {
          const filterData = async (fields: any) => {
            fields['startTime'] = moment(fields.time[0]).format('HH:mm');
            fields['endTime'] = moment(fields.time[1]).format('HH:mm');

            delete fields['time'];
            return { ...fields };
          };
          confim<PlanListReturnType>(cancelModal, addPlanMode, filterData);
        }}
      >
        <AddForm formRef={formRef} />
      </CommonModal>
    </>
  );
};

export default memo(ModalContent);
